package com.erp.database.utils;

import javax.crypto.Cipher;
import java.security.Key;


public  class DESCoder {

	private static Key getKey(byte[] arrBTmp) throws Exception {
		byte[] arrB = new byte[8];

		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");

		return key;
	}

	public static String encrypt(String keyName,String value) {
		if (value == null)
			return null;
		try {
			Key key = getKey(keyName.getBytes());

			Cipher encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);

			byte[] bs = encryptCipher.doFinal(value.getBytes());
			return byteArr2HexStr(bs);
		} catch (Exception e) {
			// Debug.logError(e, "Failed to encrypt " + value, module);
		}
		return value;
	}

	private static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	public static String decrypt(String keyName,String value) {
		if (value == null)
			return null;

		try {
			Key key = getKey(keyName.getBytes());
			Cipher decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);

			return new String(decryptCipher.doFinal(hexStr2ByteArr(value)));
		} catch (Exception e) {
			// Debug.log("Failed to decrypt " +
			// value+" And return former string:" +value);
		}
		return value;
	}

	private static  byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;

		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

}  